<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use App\Models\JuniorTeamLeader;
use App\Models\User;
use App\Models\GoldCoin;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;

class GrantSupport extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:grant-support';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.s
     *
     * @return int
     */
    public function handle()
    {

        $juniorTeamCount = cs("storm")->junior_team_number;
        $money = cs("storm")->activity_money;
        $activityOpen = cs("storm")->is_activity_open;
        JuniorTeamLeader::query()->chunk(50, function (Collection $leaders) use($juniorTeamCount,$money,$activityOpen) {

            if ($leaders->isEmpty()) return false;

            /**
             * @var User $user
             */
            foreach ($leaders as $leader) {

               $childrenCount = User::query()->where("parent_id",$leader->user_id)->where("is_gold_intern",true)->count();
               if($childrenCount >= $juniorTeamCount){
                     $teamPrize =  GoldCoin::query()->where("user_id",$leader->user_id)->where("remark","gold_record_direct_prize")->whereDate("created_at",Carbon::today())->sum("money");

                     $todayUser = GoldCoin::query()->select("from_user_id")->where("user_id",$leader->user_id)->where("remark","gold_record_direct_prize")->whereDate("created_at",Carbon::today())->get()->toArray();

                     if($todayUser){
                        $todayUserCount = count(array_unique(array_column($todayUser,'from_user_id')));
                       
                        if($activityOpen){
                            $todayCount =  $todayUserCount * $money ;

                            if($teamPrize > $todayCount ){

                                 account_coins($leader->user)->plusSupportPrizeCoins($teamPrize);
                            }else{
                                 account_coins($leader->user)->plusSupportPrizeCoins($todayCount);
                            }

                        }else{
                           
                            account_coins($leader->user)->plusSupportPrizeCoins($teamPrize);

                        }

                     }
                   

               }
            }

            return true;

        });
    }
}
